//
//  CodeViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/3/30.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class CodeViewController: BaseViewController, MBProgressHUDDelegate {

    var label: UILabel!
    var codeField: FUITextField!
    var button: FUIButton!
    
    var phoneNum: String!
    var password: String!
    
    var hud: MBProgressHUD!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.title = "注册"
        
        InitViews()
    }
    
    
    func sign(){
        let signVC = PhoneNumViewController()
        self.navigationController?.pushViewController(signVC, animated: true)
    }
    
    /**
     初始化控件
     */
    func InitViews() {
        
        label = UILabel.init(frame: CGRect(x: 20, y: 94, width: screenW - 40, height: 30))
        label.backgroundColor = UIColor.clear
        label.font = UIFont.systemFont(ofSize: 16)
        label.textColor = textlight
        label.textAlignment = NSTextAlignment.left
        label.text = "输入您的邀请码"
        
        codeField = FUITextField.init(frame: CGRect(x: 20, y: label.frame.maxY + 10, width: screenW - 40, height: 40))
        codeField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
        codeField.layer.borderWidth = 1.0
        codeField.layer.cornerRadius = 3.0
        codeField.borderColor = barColor
        codeField.borderWidth = 2.0
        codeField.cornerRadius = 3.0
        codeField.textFieldColor = UIColor.white
        codeField.backgroundColor = UIColor.clear
        codeField.font = UIFont.systemFont(ofSize: 16)
        codeField.edgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 8.0)
        codeField.placeholder = "请输入您的邀请码"
        
        button = FUIButton.init(frame: CGRect(x: 20, y: codeField.frame.maxY + 10, width: screenW - 40, height: 40))
        button.buttonColor = barColor
        button.shadowColor = barColor
        button.shadowHeight = 3.0
        button.cornerRadius = 4.0
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        button.setTitle("下一步", for: UIControlState())
        button.setTitleColor(UIColor.white, for: UIControlState())
        button.setTitleColor(UIColor.white, for: UIControlState.highlighted)
        button.addTarget(self, action: #selector(CodeViewController.nextBT), for: UIControlEvents.touchDown)
        
        self.view.addSubview(label)
        self.view.addSubview(codeField)
        self.view.addSubview(button)
        
    }
    
    /**
     下一步，根据邀请码获取信息
     */
    func nextBT(){
        
        codeField.resignFirstResponder()
        
        if codeField.text?.characters.count != 0 {
            getCodeInfo(codeField.text!)
        }else{
            TSMessage.showNotification(in: self, title: "提示", subtitle: "请输入邀请码，获取身份信息!", image: nil, type: TSMessageNotificationType.message, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
            TSMessage.addCustomDesignFromFile(withName: "TSMessagesDefaultDesign.json")
        }
    }
    /**
     根据邀请码获取相关信息
     
     - parameter codeNum: 邀请码
     校长注册
     webapp/apps/admin/adminwebapppi.ashx
     t=1
     XmlNode usertelxml = ndoc.SelectSingleNode("//rss/channel/tel");  手机号
     XmlNode userpwdxml = ndoc.SelectSingleNode("//rss/channel/pwd");   密码
     XmlNode invitecodexml = ndoc.SelectSingleNode("//rss/channel/invcode");   邀请码
     XmlNode phonetypexml = ndoc.SelectSingleNode("//rss/channel/phonetype");  手机类型
     
     返回值：True,False(SQL没有修改成功时返回False),"邀请码不存在，如有问题请联系桐乡教育客服！"
     */
    func getCodeInfo(_ codeNum: String){
        let tel = "<tel>" + phoneNum + "</tel><pwd>"
        let pwd = password + "</pwd><invcode>"
        let invcode = codeNum + "</invcode><phonetype>"
        let phonetype = getPhoneMode()! + "</phonetype></channel></rss>"
        let requestXML = requestHeader + "1</t>" + tel + pwd + invcode + phonetype
        
        let url = server + adminwebapppi
        let result = HttpUtils.httpPostUTF(url, with: requestXML)
        
        if result != nil {
            
            if result == "True" {
                LoginTask(phoneNum, password: password)
            }else if result == "False" {
                TSMessage.showNotification(withTitle: "绑定失败", type: TSMessageNotificationType.error)
            }else {
                TSMessage.showNotification(withTitle: "邀请码不存在，如有问题请联系\(appname)客服！", type: TSMessageNotificationType.error)
            }
            
        }else {
            
        }
    }

    /**
     异步任务登陆
     
     - parameter phone:    手机号码
     - parameter password: 用户密码
     */
    func LoginTask(_ phone: String!, password: String!) {
        hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.mode = MBProgressHUDMode.indeterminate
        hud.labelText = "绑定成功，正在配置相关信息"
        
        let queue = DispatchQueue(label: "queue")
        queue.async {
            
            
            let requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>2</t><tel>" + phone + "</tel><pwd>" + password + "</pwd></channel></rss>"
            let url = server + adminwebapppi
            var result = HttpUtils.httpPostUTF(url, with: requestXML)
            result = result?.replacingOccurrences(of: "null", with: "\"\"")
            DispatchQueue.main.async(execute: {
                if result == "false" {
                    /**
                     用户不存在
                     */
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "对不起，该手机号码尚未绑定", image: nil, type: TSMessageNotificationType.error, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                    self.hud.hide(true)
                }else if result == "手机号或密码不正确" {
                    /**
                     用户名密码不正确
                     */
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "用户名，密码不正确", image: nil, type: TSMessageNotificationType.error, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                    self.hud.hide(true)
                }else {
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)["post"]
                    if array.count != 0 {
                        for i in 0..<array.count {
                            
                            
                            let dic = array[i]
                            let username = dic["UserName"].stringValue
                            let usertype = dic["ProName"].stringValue
                            let schid = dic["SchSerid"].stringValue
                            let userid = dic["UserSerID"].stringValue
                            let schname = dic["SchName"].stringValue
                            let doname = dic["imgurl"].stringValue
                            
                            let defaults = UserDefaults.standard
                            let user = UserPojo()
                            user.userphone = phone
                            user.userpassword = password
                            user.username = username
                            user.usertype = usertype
                            user.schid = schid
                            user.userid = userid
                            user.schname = schname
                            user.doname = doname
                            
                            defaults.set(user.userphone!, forKey: "userphone")
                            defaults.set(user.userpassword!, forKey: "password")
                            defaults.set(user.userid!, forKey: "userid")
                            defaults.set(user.username!, forKey: "username")
                            defaults.set(user.usertype!, forKey: "usertype")
                            defaults.set(user.schid!, forKey: "schid")
                            defaults.set(user.schname!, forKey: "schname")
                            defaults.set(user.doname!, forKey: "doname")
                            defaults.synchronize()
                            
                            
                            let requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>37</t><sch>\(user.schid!)</sch><uid>\(user.userid!)</uid></channel></rss>"
                            let url = server + adminwebapppi
                            HttpPostUTF(url, requestXML: requestXML, finished: { (data, result, error) in
                                if error == nil {
                                    
                                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                                    let rightArray = NSMutableArray()
                                    initLocationData()
                                    if array.count != 0 {
                                        rightArray.addObjects(from: array.arrayObject!)
                                    }
                                    setRightArray(rightArray)
                                    let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
                                    myDelegate.goToMain()
                                }else{
                                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                                    self.hud.hide(true)
                                }
                            })
                            
                        }
                    }
                }
            })
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        codeField.resignFirstResponder()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
